package com.heying.springcore.aop.jdbc.repository.jdbc;

import com.heying.springcore.aop.jdbc.entity.StudentInfo;
import com.heying.springcore.aop.jdbc.repository.ClassRepository;
import com.heying.springcore.aop.jdbc.repository.StudentRepository;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Repository;

import javax.inject.Inject;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;

@Repository
public class JdbcStudentRepository implements StudentRepository {

    private JdbcTemplate jdbcTemplate;

    private ClassRepository classRepository;



    @Inject
    public JdbcStudentRepository(JdbcTemplate jdbcTemplate,ClassRepository classRepository) {
        this.jdbcTemplate = jdbcTemplate;
        this.classRepository = classRepository;
    }

    @Override
    public void insertOne(StudentInfo studentInfo){
        jdbcTemplate.update("insert into test01.tbl_studentinfo values(?,?,?,?,?,?)",
                studentInfo.getStuno(),
                studentInfo.getStuname(),
                studentInfo.getStubirth(),
                studentInfo.getStusex(),
                studentInfo.getStuaddr(),
                studentInfo.getStutel());
    }

    @Override
    public StudentInfo queryByStuno(String stuno){
        return jdbcTemplate.queryForObject("select * from test01.tbl_studentinfo where stuno=?",
                this::mapToStudent,stuno);
    }

//    @Override
//    public List<StudentInfo> queryAllStuAndClass(){
//        return jdbcTemplate.queryForObject("select * from test01.tbl_studentinfo where stuno=?",
//                this::mapToStudentAndClass,stuno);
//    }
    @Override
    public List<StudentInfo> queryAllStuAndClass(String stuno) {
            return null;
    }


    public StudentInfo queryStuAndClassByStuno(String stuno){
        return jdbcTemplate.queryForObject("select * from test01.tbl_studentinfo where stuno=?",
                this::mapToStudentAndClass,stuno);
    }



    private StudentInfo mapToStudentAndClass(ResultSet rs,int row) throws SQLException {
        System.out.println("row"+row);
        return new StudentInfo(rs.getString("stuno"),
                rs.getString("stuname"),
                rs.getDate("stubirth"),
                rs.getInt("stusex"),
                rs.getString("stuaddr"),
                rs.getString("stutel"),
                classRepository.queryClassByStuno(rs.getString("stuno"))
            );

    }

    private StudentInfo mapToStudent(ResultSet rs,int row) throws SQLException {
        System.out.println("row"+row);
        return new StudentInfo(rs.getString("stuno"),
                rs.getString("stuname"),
                rs.getDate("stubirth"),
                rs.getInt("stusex"),
                rs.getString("stuaddr"),
                rs.getString("stutel"));
    }
}
